<?php
function timeMeasure(){list($msec, $sec) = explode(chr(32), microtime()); return ($sec+$msec);}
define('TIMESTART', timeMeasure());//Определяем константу в которой будем хранить время старта

require_once '../php/include/global.php';
require_once 'include/basic.php';
require_once 'include/db_credentials.inc';
//error_reporting (E_ALL);
set_time_limit(60*60);
$process1 = 0;
$process2 = 0;
$process3 = 0;
$process4 = 0;
$refresh_count = 0;
$pusto = -1;
$in_process = getvar('stat_in_processing');
if ($in_process=="true")
{
	die();
}
function floorToHours(&$dt){
	$h = $dt->format("H");
	$dt->setTime((int)$h, 0, 0);
}

function floorToDays(&$dt){
	$h = $dt->format("H");
	$dt->setTime(0, 0);
}

function refreshProgress()
{
	global$process1;
	global$process2;
	$progress = 0.01+$process1*0.90+$process2*0.03+$process3*0.03+$process4*0.03;
	$progress = $progress*100;
	if ($refresh_count%100==0 and $process1<0.99)
		setvar('stat_in_converter',$progress);
	$refresh_count++;
}
$oPrj1 = array();
$mydbh = DbSimple_Generic::connect('mysql://stat:stat@localhost/call_stat_in');
$mydbh->query('SET NAMES utf8');
$mydbh->setErrorHandler('databaseErrorHandler');
$rows = $mydbh->select('SELECT * FROM projects');
foreach ($rows as $numRow => $row) {
    //echo $row['id'].$row['name'].'<br>';
    $pr_id = $row['id'];
    $tels = $mydbh->select('SELECT * FROM telephones WHERE pr_id=?d', $pr_id);
    $mytels = array();
    foreach ($tels as $nummtel => $tel) {
		$date1_ = new DateTime($tel['date1']);
		$date2_s = $tel['date2'];
		$date2_ = new DateTime($date2_s);
		if ($date2_s=="0000-00-00")
			$date2_ = new DateTime("now");
    	$mytels[$tel['id']] = array('NUMBER'=>$tel['tel'], 'date1'=>$date1_, 'date2'=>$date2_);
    }
    $oPrj1[$row['id']] = array('NAME'=>$row['name'], 'ANUMBER'=>'/.*/', 'ANUMBERDIALED'=>$mytels);
    //print_r($oPrj1[$row['id']]);
    //echo '<br>';
}
$QUALITY = $_POST['opt']['quality_sec'];
setvar('QUALITY', $QUALITY);
$QUALITY = $QUALITY/86400;

$dbFrom = $_POST['db']['queue_from'];
$dbTo   = $_POST['db']['queue_to'];

$t1=$dbFrom;
$t2=$dbTo;
dt_parse($t1);
dt_parse($t2);$t2=(int)$t2+1;
$dbWhere = "DATETIME>='{$t1}' AND DATETIME<'{$t2}'";
$dbQuery = "SELECT CALLRESULT,B1WAITLENGTH,SUMOPERLENGTH,SUMEXTERNALLENGTH,DATETIME,DATETIME_D,ANUMBERDIALED FROM I_STATISTICS_CALL_IN WHERE {$dbWhere} ORDER BY DATETIME";
$dbCountQuery = "SELECT COUNT(*) FROM I_STATISTICS_CALL_IN WHERE {$dbWhere}";
$isminup = (isset($_POST['opt']['minup']));
if ($isminup)
	setvar('isminup', 'true');
else
	setvar('isminup', 'false');
//unset($t1,$t2);
//DB OPERATIONS
$STAT = array();
$STATDAYS = array();
$STATFOOT = array();
$STATCOM = array();
$STATDAYFOOT = array();
$dbHandler = @ibase_connect($db_host, $db_user, $db_password);
echo $dbQuery."<br>";
die();
$dbResult = ibase_query($dbHandler, $dbQuery);
$dbCountResult = ibase_query($dbHandler, $dbCountQuery);
$process1 = 0;
$process2 = 0;
$process3 = 0;
$rowsCount = current(ibase_fetch_row($dbCountResult));
//echo $rowsCount."<br>";
$rowNum = 0;
setvar('stat_in_processing', 'true');
while($aRow = ibase_fetch_assoc($dbResult)){
	$process1 = $rowNum/$rowsCount;
	refreshProgress();
	$dt = dt_conv_my($aRow['DATETIME']);
	$d = dt_conv_my($aRow['DATETIME_D']);
	floorToHours($dt);
	// $dt = dt_conv_my($aRow['DATETIME']);
	// $d = $dt;
	// $d->setTime(0, 0, 0);
	// floorToHours($dt);
	parserow($aRow,&$STATCOM[$dt->getTimestamp()]);
	//echo $dt->format('Y-m-d H:i:s');
	//echo $dt->getTimestamp();
	//$rDT->setTimestamp($qwer);
	//echo $rDT->format('Y-m-d H:i:s');
	//parserow($aRow,$STAT[$dt->getTimestamp()]);
	//parserow($aRow,$STATDAYS[$d->getTimestamp()]);
	//parserow($aRow,$STATDAYFOOT);
	foreach($oPrj1 as $pr_id=>$prInfo){
		$sName = $pr_id;
		foreach($prInfo['ANUMBERDIALED'] as $telid=>$tel)
		{
			$pattern = '/'.trim($tel['NUMBER']).'/';
			if( (preg_match($pattern,$aRow['ANUMBERDIALED']))){
				$date1 = $tel['date1'];
				$date2 = $tel['date2'];
				if (($dt>=$date1) and ($dt<=$date2))
				{
					//if(!isset($STAT[$sName]=array()));
					//print_r($aRow);
					//echo '<br>';
					parserow(&$aRow,&$STAT[$dt->getTimestamp()][$sName]);
					parserow(&$aRow,&$STATDAYS[$d->getTimestamp()][$sName]);
					//parserow(&$aRow,&$STATFOOT[$sName]);
					//break;
				}
			}
		}
	}
	$rowNum++;
}
ibase_free_result ($dbResult);
ibase_close ($dbHandler);
//!!!!!
//die();

//if( !(count($STAT) > 0) )die();

//require_once 'include/config.php';
$dbh = DbSimple_Generic::connect('mysql://stat:stat@localhost/infinity_stat');
$dbh->query('SET NAMES utf8');
$dbh->setErrorHandler('databaseErrorHandler');
function databaseErrorHandler($message, $info){
	if (!error_reporting()) return;
	echo "SQL Error: $message<br><pre>"; 
	print_r($info);
	echo "</pre>";
	exit();
}
//print_r($STAT);
$site_dt = $dbh->query('SELECT MAX(`date`) as `max_date` FROM `stat_site`');
if( isset($site_dt[0]['max_date']) ) $d2 = new DateTime($site_dt[0]['max_date']);

//save to table stat_in
$mydbh->query('DELETE FROM `stat_in` WHERE 1');
$init = array();
$myprjs = array();
$curr = 0;
foreach($STAT as $day=>$prjs){
	$dt1 = new DateTime();
	$dt1->setTimestamp($day);
	$d = $dt1->format('Y-m-d H:i:s');
	$init['datetime'] = $d;
	foreach($prjs as $name=>$arr){
		$myprjs[$name] = $name;
		$init['pr_id'] = $name;
		$init['call'] = $arr['count_all'] ? $arr['count_all']:$pusto;
		if ($arr['count_all'])
		{
			if ($isminup)
				$init['min'] = $arr['dur_opersUp'];
			else
				$init['min'] = t_conv($arr['dur_opers']);
		} else
		$init['min'] = $pusto;
		$init['waste'] = isset($arr['count_all'])?$arr['count_lost']/$arr['count_all']*100:$pusto;
		$init['service'] = isset($arr['withoutIVR'])?($arr['withoutIVR']-$arr['bad'])/$arr['withoutIVR']*100:$pusto;
		$init['bad'] = $arr['bad'];
		$init['withoutIVR'] = isset($arr['withoutIVR'])?$arr['withoutIVR']:$pusto;
		//print_r($init);
		$res123 = $mydbh->query('INSERT IGNORE INTO `stat_in`(?#) VALUES(?a)' ,array_keys($init),array_values($init));
		//print_r($res123);
		//echo '<br>';
	}
}
$dtt1 = dt_conv_my($t1);
$dtt2 = dt_conv_my($t2);
while ($dtt1<$dtt2)
{
	foreach($oPrj1 as $id=>$name)
	{
		//echo $id.' '.$dtt1->format('Y-d-m H-i-s').'<br>';
		if (isset($STAT[$dtt1->getTimestamp()][$id])!=1)
		{
			$init['datetime'] = $dtt1->format('Y-m-d H:i:s');
			$init['pr_id'] = $id;
			$init['call'] = $pusto;
			$init['min'] = $pusto;
			$init['waste'] = $pusto;
			$init['service'] = $pusto;
			$init['withoutIVR'] = $pusto;
			$res123 = $mydbh->query('insert ignore into `stat_in`(?#) values(?a)' ,array_keys($init),array_values($init));
		}
	}
	$dtt1->modify('+1 hour');
}
$process2 = 1;
refreshProgress();
//end save
//save to table stat_in_days
$mydbh->query('DELETE FROM `stat_in_days` WHERE 1');
$init1 = array();
$curr = 0;
foreach($STATDAYS as $day=>$prjs){
	$dt1 = new DateTime();
	$dt1->setTimestamp($day);
	$d = $dt1->format('Y-m-d H:i:s');
	$init1['datetime'] = $d;
	foreach($prjs as $name=>$arr){
		$init1['pr_id'] = $name;
		$init1['call'] = $arr['count_all'] ? $arr['count_all']:$pusto;
		if ($arr['count_all'])
		{
			if ($isminup)
				$init['min'] = $arr['dur_opersUp'];
			else
				$init['min'] = t_conv($arr['dur_opers']);
		} else
		$init1['min'] = $pusto;
		$init1['waste'] = isset($arr['count_all'])?$arr['count_lost']/$arr['count_all']*100:$pusto;
		$init1['service'] = isset($arr['withoutIVR'])?($arr['withoutIVR']):$pusto;
		$init1['withoutIVR'] = isset($arr['withoutIVR'])?$arr['withoutIVR']:$pusto;
		//print_r($init1);
		//echo 'before';
		$res123 = $mydbh->query('INSERT IGNORE INTO `stat_in_days`(?#) VALUES(?a)' ,array_keys($init1),array_values($init1));
		//print_r($res123);
		//echo '<br>';
	}
}
$dtt1 = dt_conv_my($t1);
$dtt2 = dt_conv_my($t2);
while ($dtt1<$dtt2)
{
	foreach($oPrj1 as $id=>$name)
	{
		//echo $id.' '.$dtt1->format('Y-d-m H-i-s').'<br>';
		if (isset($STATDAYS[$dtt1->getTimestamp()][$id])!=1)
		{
			$init1['datetime'] = $dtt1->format('Y-m-d H:i:s');
			$init1['pr_id'] = $id;
			$init1['call'] = $pusto;
			$init1['min'] = $pusto;
			$init1['waste'] = $pusto;
			$init1['service'] = $pusto;
			$init1['withoutIVR'] = $pusto;
			$res123 = $mydbh->query('insert ignore into `stat_in_days`(?#) values(?a)' ,array_keys($init1),array_values($init1));
		}
	}
	$dtt1->modify('+1 day');
}
$process3 = 1;
refreshProgress();
//end save
//save to table stat_in_com
$mydbh->query('DELETE FROM `stat_in_com` WHERE 1');
$init2 = array();
$curr = 0;
foreach($STATCOM as $day=>$arr){
	$dt1 = new DateTime();
	$dt1->setTimestamp($day);
	$d = $dt1->format('Y-m-d H:i:s');
	$init2['datetime'] = $d;
	$init2['call'] = $arr['count_all'] ? $arr['count_all']:$pusto;
		if ($arr['count_all'])
		{
			if ($isminup)
				$init2['min'] = $arr['dur_opersUp'];
			else
				$init2['min'] = t_conv($arr['dur_opers']);
		} else
		$init2['min'] = $pusto;
		$init2['waste'] = isset($arr['count_all'])?$arr['count_lost']/$arr['count_all']*100:$pusto;
		$init2['service'] = isset($arr['withoutIVR'])?($arr['withoutIVR']-$arr['bad'])/$arr['withoutIVR']*100:$pusto;
		$init2['withoutIVR'] = isset($arr['withoutIVR'])?$arr['withoutIVR']:$pusto;
	//print_r($init2);
	$res123 = $mydbh->query('INSERT IGNORE INTO `stat_in_com`(?#) VALUES(?a)' ,array_keys($init2),array_values($init2));
	//print_r($res123);
	//echo '<br>';
}
$dtt1 = dt_conv_my($t1);
$dtt2 = dt_conv_my($t2);
while ($dtt1<$dtt2)
{
	if (isset($STATCOM[$dtt1->getTimestamp()])!=1)
	{
		$init2['datetime'] = $dtt1->format('Y-m-d H:i:s');
		$init2['call'] = $pusto;
		$init2['min'] = $pusto;
		$init2['waste'] = $pusto;
		$init2['service'] = $pusto;
		$init2['withoutIVR'] = $pusto;
		$res123 = $mydbh->query('insert ignore into `stat_in_com`(?#) values(?a)' ,array_keys($init2),array_values($init2));
	}
	$dtt1->modify('+1 hour');
}
$process4 = 1;
refreshProgress();
//end save

$process1 = 1;
refreshProgress();
setvar('stat_in_processing', 'false');
$ctime = new DateTime("now");
setvar('stat_in_last_convert', $ctime->format('Y-m-d H:i:s'));
//echo '<br/>Расчет был сделан за  ',round(timeMeasure()-TIMESTART, 6),' сек.';
?>